// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use screenshots::Screen;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
fn capture_area(x: u32, y: u32, width: u32, height: u32) -> Result<(), String> {
    println!("Hello, world!");
    // 确保 x 和 y 可以安全地转换为 i32
    let x_i32 = x.try_into().map_err(|_| "X coordinate out of range")?;
    let y_i32 = y.try_into().map_err(|_| "Y coordinate out of range")?;

    let screen = Screen::from_point(x_i32, y_i32).map_err(|e| e.to_string())?;
    let image = screen.capture_area(x_i32, y_i32, width, height).map_err(|e| e.to_string())?;
    image
        .save(format!("screenshot-{}-{}.png", x, y))
        .map_err(|e: screenshots::image::ImageError| e.to_string())?;
    Ok(())
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![greet,capture_area])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
